package com.zut.util;

import com.alibaba.fastjson.JSONObject;

import com.zut.domain.EnvData;
import com.zut.service.EnvDataService;
import com.zut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Component
public class circleInsert extends Thread {
    @Autowired
    private UserService userService;

    @Autowired
    private EnvDataService envDataService;

    @Value("${spring.thingsboard.url}")
    String host;

    public circleInsert() {
        this.start();
    }

    @Override
    public void run() {
        EnvData envData = new EnvData();
        RestTemplate restTemplate = new RestTemplate();

        while (true) {
            List<String> n = userService.selectAllToken();
            if (n.size() != 0) {
                for (String l : n) {
                    try {
                        System.out.println(l);
                        String requestUrl = host + "/api/v1/" + l + "/attributes?clientKeys=distance,temperature,humidity";
                        String result = restTemplate.getForObject(requestUrl, String.class);
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        envData.setDistance(Double.parseDouble(jsonObject.getJSONObject("client").getString("distance")));
                        envData.setHumidity(Double.parseDouble(jsonObject.getJSONObject("client").getString("humidity")));
                        envData.setTemperature(Double.parseDouble(jsonObject.getJSONObject("client").getString("temperature")));
                        //获取时间戳
                        LocalDateTime now = LocalDateTime.now();
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        String formattedDateTime = now.format(formatter);
                        System.out.println(formattedDateTime);
                        envData.setTimestamp(formattedDateTime);
                        envData.setToken(l);
                        envDataService.insert(envData);
                        log();
                        //每隔5秒插入一次

                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            else {
                try {
                    Thread.sleep(5000);
                    System.out.println("表中没有数据，等待中");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void log() {
//        新建一个日志文件
        File file = new File("log.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        记录当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
//        写入日志
        try (FileWriter writer = new FileWriter(file, true)) {
            writer.write("最后记录时间" + formattedDateTime + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
